package com.liuya.log.service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuya.base.AbstractBaseService;
import com.liuya.log.SysEventService;
import com.liuya.log.model.SysEvent;

import com.liuya.common.DateUtil;
import com.liuya.common.ExceptionUtil;
import com.liuya.common.InstanceUtil;
import com.liuya.common.WebUtil;

import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

/**
 * 日志记录实现类
 *
 * @author liuya
 * @date 20160824
 */
@Service("sysEventServiceImpl")
public class SysEventServiceImpl extends AbstractBaseService<SysEvent> implements SysEventService {
//    @DubboReference
//    public void setProvider(SysEventProvider provider) {
//        this.provider = provider;
//    }

    private ExecutorService executorService = Executors.newCachedThreadPool();

//    @Autowired
//    private SysEventMapper sysEventMapper;

//    @Autowired
//    @Qualifier("sysEventMapper")
//    private SysEventMapper sysEventMapper;

//    @Autowired
//    private @Qualifier("sysEventMapper") SysEventMapper sysEventMapper;

//    @Resource(name = "sysEventMapper")
//    private SysEventMapper sysEventMapper;

//    @Resource(name = "sysEventMapper")
//    public void setMapper(SysEventMapper sysEventMapper) {
//        this.mapper = sysEventMapper;
//    }

//    @Autowired
//    @Qualifier("sysEventMapper")
//    public void setMapper(SysEventMapper sysEventMapper) {
//        this.mapper = sysEventMapper;
//    }

//    @Autowired
//    public void setMapper(@Qualifier("sysEventMapper")SysEventMapper sysEventMapper) {
//        this.mapper = sysEventMapper;
//    }

    public void saveEvent(final HttpServletRequest request, final HttpServletResponse response,
                          final Exception ex, final Long startTime, final Long endTime) {
        final SysEvent record = new SysEvent();
//        String uid = WebUtil.getCurrentUser();
        String uid = "123456789";
//        record.setId(String.valueOf(System.currentTimeMillis()));
        record.setMethod(request.getMethod());
        record.setRequestUri(request.getServletPath());
        record.setClientHost(WebUtil.getHost(request));
        record.setUserAgent(request.getHeader("user-agent"));
        record.setParameters(JSON.toJSONString(request.getParameterMap()));
        record.setStatus(response.getStatus());
        record.setCreateTime(new Date());
        record.setCreateBy(uid);
        record.setUpdateBy(uid);
        record.setUpdateTime(new Date());
//        mapper.insert(record);
//        sysEventMapper.insert(record);
//        Map<String, Object> params = new HashedMap();
//        provider.query(params);

        final String msg = (String) request.getAttribute("msg");

        executorService.submit(new Runnable() {
            public void run() {
                try { // 保存操作
                    if (StringUtils.isNotBlank(msg)) {
                        record.setRemark(msg);
                    } else {
                        record.setRemark(ExceptionUtil.getStackTraceAsString(ex));
                    }
                    Map<String, Object> params = InstanceUtil.newHashMap();
                    params.put("permission_url", record.getRequestUri());

                    add(record);
                    // 内存信息
                    if (logger.isDebugEnabled()) {
                        String message = "开始时间: {}; 结束时间: {}; 耗时: {}s; URI: {}; ";
                        // 最大内存: {}M; 已分配内存: {}M; 已分配内存中的剩余空间: {}M; 最大可用内存: {}M.
                        // long total = Runtime.getRuntime().totalMemory() / 1024 / 1024;
                        // long max = Runtime.getRuntime().maxMemory() / 1024 / 1024;
                        // long free = Runtime.getRuntime().freeMemory() / 1024 / 1024;
                        // , max, total, free, max - total + free
                        logger.debug(message, DateUtil.format(startTime, "HH:mm:ss.SSS"),
                                DateUtil.format(endTime, "HH:mm:ss.SSS"),
                                (endTime - startTime) / 1000.00, record.getRequestUri());
                    }
                } catch (Exception e) {
                    logger.error("保存事件日志时发生错误:", e);
                }
            }
        });
    }

}
